package start

import (
	"fmt"
	"gitee.com/filters/logger"
	"gitee.com/filters/reader/wviper"
	"gitee.com/filters/start/proxy"
	"gitee.com/filters/start/safe_map"
	"google.golang.org/grpc/encoding"
	"google.golang.org/grpc/reflection"
	//"gitee.com/filters/start/proxy"
	"gitee.com/filters/start/refer"
	"gitee.com/filters/utils/conversion"
	"google.golang.org/grpc"
	//"google.golang.org/grpc/encoding"
	//"google.golang.org/grpc/reflection"
	"net"
	"reflect"
)

const (
	GrpcCfg     = "Grpcserver"
	GrpcCrtPath = "crt_path"
	GrpcKeyPath = "key_path"
)

type GrpcServer struct {
	//srv:service|RegisterFileUploadServiceServer:&Server{}
	srvMap     []GrpcCfgMap
	grpcConfig safe_map.ConfigSafeMap
}

type GrpcCfgMap struct {
	Srv
	Service
	SrvDesc
}

type Srv interface{}
type Service interface{}
type SrvDesc interface{}

func NewGrpc(srvMap []GrpcCfgMap, opt ...wviper.Option) *GrpcServer {
	s := &GrpcServer{
		srvMap: srvMap,
	}
	err := s.LoadConfig(opt...)
	if err != nil {
		panic(err)
	}
	return s
}

func (g *GrpcServer) LoadConfig(opt ...wviper.Option) error {
	cfg, err := wviper.NewSetting(opt...)
	if err != nil {
		return err
	}
	config = cfg
	if _, ok := cfg.Get(GrpcCfg).(map[string]interface{}); !ok {
		return refer.ErrorNotFoundConfigInfo
	}
	g.grpcConfig.Data = cfg.Get(GrpcCfg).(map[string]interface{})
	return nil
}

// UseLog 日志记录
func (g *GrpcServer) UseLog() *GrpcServer {
	cfg := config.Get(logger.Logger).(map[string]interface{})
	logger.NewLog(logger.WithWritePath(cfg[logger.LogPathName].(string)),
		logger.WithLogExt(cfg[logger.LogExtName].(string))).CurLog().WrapFormat()
	return g
}

// BindField 绑定数据
func (g *GrpcServer) BindField(f ...interface{}) *GrpcServer {
	for _, i2 := range f {
		conversion.ToStruct(config.AllSettings(), i2)
	}
	return g
}

func (g *GrpcServer) Run() error {
	lis, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", g.grpcConfig.Get(GrpcPort)))
	if err != nil {
		return err
	}
	// 实例化grpc服务端
	encoding.RegisterCodec(proxy.JSON{})
	//var creds credentials.TransportCredentials
	//if _, ok := g.grpcConfig[GrpcCrtPath]; ok {
	//	if _, ok1 := g.grpcConfig[GrpcKeyPath]; ok1 {
	//		cert, err := tls.LoadX509KeyPair(g.grpcConfig[GrpcCrtPath].(string), g.grpcConfig[GrpcKeyPath].(string))
	//		if err != nil {
	//			return err
	//		}
	//
	//		creds = credentials.NewServerTLSFromCert(&cert)
	//	}
	//
	//}
	// 设置grpc服务端选项
	conn := grpc.NewServer()
	//if creds != nil {
	//	fmt.Println("grpc server tls")
	//	conn = grpc.NewServer(grpc.Creds(creds))
	//}
	for _, v := range g.srvMap {
		// 反射注册Grpc服务
		ss := reflect.ValueOf(v.Srv)
		args := []reflect.Value{reflect.ValueOf(conn), reflect.ValueOf(v.Service)}
		ss.Call(args)
	}

	// 往grpc服务端注册反射服务
	reflection.Register(conn)
	fmt.Printf("grpc server:%s \n", fmt.Sprintf("http://127.0.0.1:%d", g.grpcConfig.Get(GrpcPort)))
	// 启动grpc服务
	if err := conn.Serve(lis); err != nil {
		return err
	}
	return nil
}
